<?php
/**
 * Created by PhpStorm.
 * User: lili
 * Date: 2018/11/16
 * Time: 15:43
 *
 * 登录功能的控制器
 *
 *
 */

namespace app\index\controller;



use app\index\model\User;
use think\Controller;

class Login extends Controller
{


    /*
     * 登录验证
     * @access public
     * @param string username 用户名
     * @param int sex 性别 1是男，2是女
     * @param int age 年龄
     * @param double height 身高
     * @param double weight 体重
     * @return json
     *
     *
     * */
    /*public function login(){
        if(request()->isPost()){
            $send = input('post.','','htmlspecialchars,strip_tags,trim');
            $user = new \app\index\model\User();
            $uv = new \app\index\validate\User();
            if ($uv->check($send)){
                if( $user =  $user->isUser($send)){
                    //存在这个用户
                    //产生token
                    $token = generateToken($user['uid']);
                    cache('token',$token,7200);
                    cache($token,$user,7200);
                    rjson(100,'登录成功',array(
                        'token'=>$token,
                        'user'=>$user
                    ));
                }else{
                    rjson(110,'不存在该用户');
                }
            }else{
                rjson(110,$uv->getError());
            }


        }else{
            rjson(110,'必须post请求');
        }
        
    }*/


    /*
     * 产生token
     * @param [string] $openid [微信小程序登录的openid]
     * @return  json token 和基本的用户信息
     *
     * */
    public function getToken(){
        if (empty($_POST['openid'])) {
            echo json_encode(array('code'=>110,'msg'=>'openid不可为空！'));
            exit();
        }
        $openid = $_POST['openid'];
        $con = array();
        $con['openid']=trim($openid);
        $user = new  User();
        $u = $user->where($con)->find();
        if (!empty($u)) {
            $token = generateToken($openid);
            cache('token',$token,720000);
            cache($token,$u,720000);
            rjson(100,'获取token成功',array(
                'token'=>$token,
                'user'=>$u
            ));
        }else{
            rjson(110,'openid不存在');
        }

    }





    /*
     * [授权登录接口，加入数据库]
     * @param [string] $openid [微信小程序登录的openid]
     * @param [string] $NickName [昵称]
     * @param [string] $HeadUrl [头像]
     * @param [string] $gender [性别]
     * */
    public function authlogin(){
//        var_dump($_POST);

        if (empty($_POST['openid'])) {
            echo json_encode(array('code'=>110,'msg'=>'授权失败！'));
            exit();
        }
        $openid = $_POST['openid'];
        $con = array();
        $con['openid']=trim($openid);
        $user = new  User();
        $u = $user->where($con)->find();

//        var_dump($uid);
        if (!empty($u)) {
            $uid = $u['uid'];
            $userinfo = $user->where('uid='.intval($uid))->find();
            if (empty($userinfo)) {
                echo json_encode(array('code'=>110,'msg'=>'账号状态异常！'));
                exit();
            }
            $err = array();
            $err['ID'] = intval($uid);
            $err['NickName'] = $userinfo['nick'];
            $err['HeadUrl'] = $userinfo['photo'];
            $err['username'] = $userinfo['username'];
            $err['age'] = $userinfo['age'];
            $err['sex'] = $userinfo['sex'];
            $err['height'] = $userinfo['height'];
            $err['weight'] = $userinfo['weight'];
            echo json_encode(array('code'=>100,'msg'=>'获得已有用户数据！','result'=>$err));
            exit();
        }else{
            $uid = $u['uid'];
            $data = array();
            $data['nick'] = $_POST['NickName'];
            $data['photo'] = $_POST['HeadUrl'];
            $data['sex'] = $_POST['gender'];
            $data['openid'] = $openid;
            //$data['addtime'] = time();
            if (!$data['openid']) {
                echo json_encode(array('code'=>110,'msg'=>'授权失败！','result' => ''));
                exit();
            }
            //$res = M('user')->add($data);
//            var_dump($data);
            $res = $user->isUpdate(false)->save($data);
//            var_dump($res);
            if ($res) {
                $err = array();
                $err['ID'] = intval($user->uid);
                $err['NickName'] = $data['nick'];
                $err['HeadUrl'] = $data['photo'];
                $err['username'] = $res['username'];
                $err['age'] = $res['age'];
                $err['sex'] = $res['sex'];
                $err['height'] = $res['height'];
                $err['weight'] = $res['weight'];
                echo json_encode(array('code'=>100,'msg'=>'获得刚增加的用户数据！','result'=>$err));
                exit();
            }else{
                echo json_encode(array('code'=>110,'msg'=>'授权失败！','result' => ''));
                exit();
            }
        }
    }





    /*
     * [获取sessionkey 接口]
     * @param [string] $code [微信小程序登录的code]
     * @return json [sessionkey 和 openid]
     *
     *
     * */
    public function getsessionkey(){


        $appid = config('sys.appid');
        $secret = config('sys.appsecret');
//        var_dump($wx_config);
        $code = trim($_POST['code']);
        if (!$code) {
            echo json_encode(array('code'=>0,'msg'=>'非法操作！','result' => ''));
            exit();
        }

        if (!$appid || !$secret) {
            echo json_encode(array('code'=>0,'msg'=>'非法操作！','result' => ''));
            exit();
        }

        $get_token_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
//		dump($get_token_url);
        /*$ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$get_token_url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        //curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $res = curl_exec($ch);
        curl_close($ch);*/
        $ch = curl_init();
        // 2. 设置选项，包括URL
        curl_setopt($ch,CURLOPT_URL,$get_token_url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // 3. 执行并获取HTML文档内容
        $output = curl_exec($ch);
        if($output === FALSE ){
            echo json_encode(array('code'=>110,'msg'=>'CURL Error：'.curl_error($ch),'result' => array() ));
            echo "CURL Error:".curl_error($ch);
        }
        // 4. 释放curl句柄
        curl_close($ch);
//		dump($output);
        echo json_encode(array('code'=>100,'msg'=>'返回sessionkey','result' => json_decode($output,true) ));
//        echo $output;
        exit();
    }

    




}